<!DOCTYPE html>

































































<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="shortcut icon" type="image/x-icon" href="../../../favicon.ico" />
<title>Activities | Android Developers</title>
<link href="../../../assets/android-developer-docs-devguide.css" rel="stylesheet" type="text/css" />
<script src="../../../assets/search_autocomplete.js" type="text/javascript"></script>
<script src="../../../assets/jquery-resizable.min.js" type="text/javascript"></script>
<script src="../../../assets/android-developer-docs.js" type="text/javascript"></script>
<script src="../../../assets/prettify.js" type="text/javascript"></script>
<script type="text/javascript">
  setToRoot("../../../");
</script>
<noscript>
  <style type="text/css">
    html,body{overflow:auto;}
    #body-content{position:relative; top:0;}
    #doc-content{overflow:visible;border-left:3px solid #666;}
    #side-nav{padding:0;}
    #side-nav .toggle-list ul {display:block;}
    #resize-packages-nav{border-bottom:3px solid #666;}
  </style>
</noscript>
</head>
<body class="gc-documentation">

  <div id="header">
      <div id="headerLeft">
          <a href="../../../index.html" tabindex="-1"><img
              src="../../../assets/images/bg_logo.png" alt="Android Developers" /></a>
          <ul id="header-tabs" class="guide">
    
	<li id="home-link"><a href="../../../offline.html">
	
		<span class="en">Home</span>
		<span style="display:none" class="de">Startseite</span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ホーム</span>
		<span style="display:none" class="zh-CN">主页</span>
		<span style="display:none" class="zh-TW">首頁</span>
	
	</a></li>
	<li id="sdk-link"><a href="../../../sdk/index.html">
		<span class="en">SDK</span>
	</a></li>
	<li id="guide-link"><a href="../../../guide/index.html" onClick="return loadLast('guide')">
	
		<span class="en">Dev Guide</span>
		<span style="display:none" class="de">Handbuch</span>
		<span style="display:none" class="es">Guía</span>
		<span style="display:none" class="fr">Guide</span>
		<span style="display:none" class="it">Guida</span>
		<span style="display:none" class="ja">開発ガイド</span>
		<span style="display:none" class="zh-CN">开发人员指南</span>
		<span style="display:none" class="zh-TW">開發指南</span>
	
	</a></li>
	<li id="reference-link"><a href="../../../reference/packages.html" onClick="return loadLast('reference')">
	
		<span class="en">Reference</span>
		<span style="display:none" class="de">Referenz</span>
		<span style="display:none" class="es">Referencia</span>
		<span style="display:none" class="fr">Référence</span>
		<span style="display:none" class="it">Riferimento</span>
		<span style="display:none" class="ja">リファレンス</span>
		<span style="display:none" class="zh-CN">参考</span>
		<span style="display:none" class="zh-TW">參考資料</span>
	
	</a></li>
	<li id="resources-link"><a href="../../../resources/index.html" onClick="return loadLast('resources')">
	
		<span class="en">Resources</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
    		<span style="display:none" class="ja"></span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li id="videos-link"><a href="../../../videos/index.html" onClick="return loadLast('videos')">
	
		<span class="en">Videos</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ビデオ</span>
		<span style="display:none" class="zh-CN"></span>
		<span style="display:none" class="zh-TW"></span>
	
	</a></li>
	<li><a href="http://android-developers.blogspot.com" onClick="return requestAppendHL(this.href)">
	
		<span class="en">Blog</span>
		<span style="display:none" class="de"></span>
		<span style="display:none" class="es"></span>
		<span style="display:none" class="fr"></span>
		<span style="display:none" class="it"></span>
		<span style="display:none" class="ja">ブログ</span>
		<span style="display:none" class="zh-CN">博客</span>
		<span style="display:none" class="zh-TW">網誌</span>
	
	</a></li>


     
</ul>
     
      </div>
      <div id="headerRight">
          <div id="headerLinks">
          
          <a href="http://www.android.com">Android.com</a>
          </div>
  <div id="search" >
      <div id="searchForm">
          <form accept-charset="utf-8" class="gsc-search-box" 
                onsubmit="return submit_search()">
            <table class="gsc-search-box" cellpadding="0" cellspacing="0"><tbody>
                <tr>
                  <td class="gsc-input">
                    <input id="search_autocomplete" class="gsc-input" type="text" size="33" autocomplete="off"
                      title="search developer docs" name="q"
                      value="search developer docs"
                      onFocus="search_focus_changed(this, true)"
                      onBlur="search_focus_changed(this, false)"
                      onkeydown="return search_changed(event, true, '../../../')"
                      onkeyup="return search_changed(event, false, '../../../')" />
                  <div id="search_filtered_div" class="no-display">
                      <table id="search_filtered" cellspacing=0>
                      </table>
                  </div>
                  </td>
                  <td class="gsc-search-button">
                    <input type="submit" value="Search" title="search" id="search-button" class="gsc-search-button" />
                  </td>
                  <td class="gsc-clear-button">
                    <div title="clear results" class="gsc-clear-button">&nbsp;</div>
                  </td>
                </tr></tbody>
              </table>
          </form>
      </div><!-- searchForm -->
  </div><!-- search -->
      </div><!-- headerRight -->
      <script type="text/javascript">
        <!--  
        changeTabLang(getLangPref());
        //-->
      </script>
  </div><!-- header -->

  <div class="g-section g-tpl-240" id="body-content">
    <div class="g-unit g-first" id="side-nav">
      <div id="devdoc-nav">
<ul>

  <li>
    <h2><span class="en">Android Basics</span>
        <span class="de" style="display:none">Einführung in Android</span>
        <span class="es" style="display:none">Información básica sobre Android</span>
        <span class="fr" style="display:none">Présentation d'Android</span>
        <span class="it" style="display:none">Nozioni di base su Android</span>
        <span class="ja" style="display:none">Android の基本</span>
        <span class="zh-CN" style="display:none">Android 基础知识</span>
        <span class="zh-TW" style="display:none">Android 簡介</span>
    </h2>
    <ul>
      <li><a href="../../../guide/basics/what-is-android.html">
        <span class="en">What Is Android?</span>
        <span class="de" style="display:none">Was ist Android?</span>
        <span class="es" style="display:none">¿Qué es Android?</span>
        <span class="fr" style="display:none">Qu'est-ce qu'Android&nbsp;?</span>
        <span class="it" style="display:none">Che cos'è Android?</span>
        <span class="ja" style="display:none">Android とは</span>
        <span class="zh-CN" style="display:none">Android 是什么？</span>
        <span class="zh-TW" style="display:none">什麼是 Android？</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals.html">
        <span class="en">Application Fundamentals</span>
        <span class="de" style="display:none">Anwendungsgrundlagen</span>
        <span class="es" style="display:none">Fundamentos de las aplicaciones</span>
        <span class="fr" style="display:none">Principes de base des applications</span>
        <span class="it" style="display:none">Concetti fondamentali sulle applicazioni</span>
        <span class="ja" style="display:none">開発の基礎</span>
        <span class="zh-CN" style="display:none">应用程序基础</span>
        <span class="zh-TW" style="display:none">應用程式基本原理</span>
      </a></li>

  <!--  <li><a style="color:gray;">The Android SDK</a></li> -->
  <!--  <li><a style="color:gray;">Walkthrough for Developers</a></li> -->
      <!-- quick overview of what it's like to develop on Android -->
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Framework Topics</span>
      <span class="de" style="display:none">Framework-Themen</span>
      <span class="es" style="display:none">Temas sobre el framework</span>
      <span class="fr" style="display:none">Thèmes relatifs au framework</span>
      <span class="it" style="display:none">Argomenti relativi al framework</span>
      <span class="ja" style="display:none">フレームワーク トピック</span>
      <span class="zh-CN" style="display:none">框架主题</span>
      <span class="zh-TW" style="display:none">架構主題</span>
    </h2>
    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/activities.html">
          <span class="en">Activities</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/fragments.html">
            <span class="en">Fragments</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/loaders.html">
            <span class="en">Loaders</span>
          </a></li>
          <li><a href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">
            <span class="en">Tasks and Back Stack</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/fundamentals/services.html">
          <span class="en">Services</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/fundamentals/bound-services.html">
            <span class="en">Bound Services</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/topics/providers/content-providers.html">
            <span class="en">Content Providers</span>
          </a></li>
      <li><a href="../../../guide/topics/intents/intents-filters.html">
            <span class="en">Intents and Intent Filters</span>
          </a></li>
      <li><a href="../../../guide/topics/fundamentals/processes-and-threads.html">
            <span class="en">Processes and Threads</span>
          </a></li>
    </ul>


    <ul>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/ui/index.html">
            <span class="en">User Interface</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/ui/declaring-layout.html">
               <span class="en">XML Layouts</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/ui-events.html">
                <span class="en">Input Events</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/menus.html">
               <span class="en">Menus</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/actionbar.html">
               <span class="en">Action Bar</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/dialogs.html">
                <span class="en">Dialogs</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/ui/notifiers/index.html">
                <span class="en">Notifications</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/ui/notifiers/toasts.html">
                <span class="en">Toast Notifications</span>
              </a></li>
              <li><a href="../../../guide/topics/ui/notifiers/notifications.html">
                <span class="en">Status Bar Notifications</span>
              </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/topics/ui/drag-drop.html">
                <span class="en">Drag and Drop</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/themes.html">
                <span class="en">Styles and Themes</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/custom-components.html">
                <span class="en">Custom Components</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/binding.html">
                <span class="en">Binding to Data with AdapterView</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/layout-objects.html">
                <span class="en">Common Layout Objects</span>
              </a></li>
          <li><a href="../../../guide/topics/ui/how-android-draws.html">
                <span class="en">How Android Draws Views</span>
              </a></li>
        </ul>
      </li><!-- end of User Interface -->

      <li class="toggle-list">
        <div><a href="../../../guide/topics/resources/index.html">
               <span class="en">Application Resources</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/resources/providing-resources.html">
                <span class="en">Providing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/accessing-resources.html">
                <span class="en">Accessing Resources</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/runtime-changes.html">
                <span class="en">Handling Runtime Changes</span>
              </a></li>
          <li><a href="../../../guide/topics/resources/localization.html">
                <span class="en">Localization</span>
              </a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/topics/resources/available-resources.html">
              <span class="en">Resource Types</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/topics/resources/animation-resource.html">Animation</a></li>
              <li><a href="../../../guide/topics/resources/color-list-resource.html">Color State List</a></li>
              <li><a href="../../../guide/topics/resources/drawable-resource.html">Drawable</a></li>
              <li><a href="../../../guide/topics/resources/layout-resource.html">Layout</a></li>
              <li><a href="../../../guide/topics/resources/menu-resource.html">Menu</a></li>
              <li><a href="../../../guide/topics/resources/string-resource.html">String</a></li>
              <li><a href="../../../guide/topics/resources/style-resource.html">Style</a></li>
              <li><a href="../../../guide/topics/resources/more-resources.html">More Types</a></li>
            </ul>
          </li><!-- end of resource types -->
        </ul>
      </li><!-- end of app resources -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/data/data-storage.html">
            <span class="en">Data Storage</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/data/backup.html">
                <span class="en">Data Backup</span>
              </a>
            </li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/security/security.html">
            <span class="en">Security and Permissions</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/manifest/manifest-intro.html">
          <span class="en">The AndroidManifest.xml File</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/topics/manifest/action-element.html">&lt;action&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-element.html">&lt;activity&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/activity-alias-element.html">&lt;activity-alias&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/application-element.html">&lt;application&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/category-element.html">&lt;category&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/compatible-screens-element.html">&lt;compatible-screens&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/data-element.html">&lt;data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/grant-uri-permission-element.html">&lt;grant-uri-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/instrumentation-element.html">&lt;instrumentation&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/intent-filter-element.html">&lt;intent-filter&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/manifest-element.html">&lt;manifest&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/meta-data-element.html">&lt;meta-data&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/path-permission-element.html">&lt;path-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-element.html">&lt;permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-group-element.html">&lt;permission-group&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/permission-tree-element.html">&lt;permission-tree&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/provider-element.html">&lt;provider&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/receiver-element.html">&lt;receiver&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/service-element.html">&lt;service&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-gl-texture-element.html">&lt;supports-gl-texture&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/supports-screens-element.html">&lt;supports-screens&gt;</a></li><!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-configuration-element.html">&lt;uses-configuration&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-feature-element.html">&lt;uses-feature&gt;</a></li> <!-- ##api level 4## -->
          <li><a href="../../../guide/topics/manifest/uses-library-element.html">&lt;uses-library&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-permission-element.html">&lt;uses-permission&gt;</a></li>
          <li><a href="../../../guide/topics/manifest/uses-sdk-element.html">&lt;uses-sdk&gt;</a></li>
        </ul>
      </li><!-- end of the manifest file -->
    </ul>

    <ul>
    <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/index.html">
            <span class="en">Graphics</span>
          </a><span class="new-child">new!</span></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/2d-graphics.html">
              <span class="en">Canvas and Drawables</span></a></li>
          <li><a href="../../../guide/topics/graphics/hardware-accel.html">
              <span class="en">Hardware Acceleration</span></a>
            <span class="new">new!</span></li>
          <li><a href="../../../guide/topics/graphics/opengl.html">
              <span class="en">OpenGL</span>
            </a><span class="new">updated</span></li>
        </ul>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/graphics/animation.html">
            <span class="en">Animation</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/topics/graphics/prop-animation.html">
              <span class="en">Property Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/view-animation.html">
              <span class="en">View Animation</span></a></li>
          <li><a href="../../../guide/topics/graphics/drawable-animation.html">
              <span class="en">Drawable Animation</span></a></li>
        </ul>
      </li>
      <li class="toggle-list">
	        <div><a href="../../../guide/topics/renderscript/index.html">
	            <span class="en">RenderScript</span>
	          </a></div>
	        <ul>
	          <li><a href="../../../guide/topics/renderscript/graphics.html">
	                <span class="en">Graphics</span>
	              </a>
	          </li>
	          <li><a href="../../../guide/topics/renderscript/compute.html">
	                <span class="en">Compute</span>
	              </a>
	          </li>
	        </ul>
  	  </li>

      <li class="toggle-list">
          <div><a href="../../../guide/topics/media/index.html">
            <span class="en">Multimedia and Camera</span>
          </a><span class="new">updated</span></div>
          <ul>
            <li><a href="../../../guide/topics/media/mediaplayer.html">
                  <span class="en">Media Playback</span></a>
                </li>
            <li><a href="../../../guide/topics/media/jetplayer.html">
                  <span class="en">JetPlayer</span></a>
                </li>
            <li><a href="../../../guide/topics/media/camera.html">
                  <span class="en">Camera</span></a>
                  <span class="new">new!</span>
                </li>
            <li><a href="../../../guide/topics/media/audio-capture.html">
                  <span class="en">Audio Capture</span></a>
                </li>
          </ul>
      </li>
      <li>
        <a href="../../../guide/topics/clipboard/copy-paste.html">
            <span class="en">Copy and Paste</span>
        </a></li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Sensors</a></div>
          <ul>
            <li><a style="color:gray;">Camera</a></li>
            <li><a style="color:gray;">Compass</a></li>
            <li><a style="color:gray;">Accelerometer</a></li>
          </ul>
      </li> -->
      <li class="toggle-list">
        <div><a href="../../../guide/topics/location/index.html">
               <span class="en">Location and Maps</span>
             </a></div>
        <ul>
          <li><a href="../../../guide/topics/location/obtaining-user-location.html">
                <span class="en">Obtaining User Location</span>
              </a></li>
        </ul>
      </li>
  <!--<li class="toggle-list">
        <div><a style="color:gray;">Wireless Controls</a></div>
          <ul>
            <li><a style="color:gray;">Wi-Fi</a></li>
          </ul>
      </li> -->
  <!--<li><a style="color:gray;">Localization</a></li>  -->
      <li><a href="../../../guide/topics/appwidgets/index.html">
            <span class="en">App Widgets</span></a>
          </li>
      <li><a href="../../../guide/topics/wireless/bluetooth.html">
            <span class="en">Bluetooth</span></a>
          </li>
      <li><a href="../../../guide/topics/nfc/index.html">
            <span class="en">Near Field Communication</span>
          </a></li>
      <li class="toggle-list">
          <div><a href="../../../guide/topics/usb/index.html">
            <span class="en">USB</span></a>
          </div>
            <ul>
              <li><a href="../../../guide/topics/usb/accessory.html">Accessory</a></li>
              <li><a href="../../../guide/topics/usb/host.html">Host</a></li>
              <li><a href="../../../guide/topics/usb/adk.html">Open Accessory Dev Kit</a></li>
            </ul>
          </li>

       <li><a href="../../../guide/topics/network/sip.html">
            <span class="en">Session Initiation Protocol</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/topics/search/index.html">
            <span class="en">Search</span>
          </a></div>
          <ul>
            <li><a href="../../../guide/topics/search/search-dialog.html">Creating a Search Interface</a></li>
            <li><a href="../../../guide/topics/search/adding-recent-query-suggestions.html">Adding Recent Query Suggestions</a></li>
            <li><a href="../../../guide/topics/search/adding-custom-suggestions.html">Adding Custom Suggestions</a></li>
            <li><a href="../../../guide/topics/search/searchable-config.html">Searchable Configuration</a></li>
          </ul>
      </li>
      <li><a href="../../../guide/topics/admin/device-admin.html">
            <span class="en">Device Administration</span></a>
      </li>
      <li class="toggle-list">
           <div>
                <a href="../../../guide/topics/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/topics/testing/testing_android.html">
                <span class="en">Testing Fundamentals</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/activity_testing.html">
                <span class="en">Activity Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/contentprovider_testing.html">
                <span class="en">Content Provider Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/service_testing.html">
                <span class="en">Service Testing</span></a>
              </li>
              <li>
                <a href="../../../guide/topics/testing/what_to_test.html">
                <span class="en">What To Test</span></a>
              </li>
           </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2>
      <span class="en">Android Market Topics</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/licensing.html">
          <span class="en">Application Licensing</span></a>
      </li>
      <li class="toggle-list">
        <div><a href="../../../guide/market/billing/index.html">
            <span class="en">In-app Billing</span></a>
        </div>
        <ul>
          <li><a href="../../../guide/market/billing/billing_overview.html">
              <span class="en">In-app Billing Overview</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_integrate.html">
              <span class="en">Implementing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_best_practices.html">
              <span class="en">Security and Design</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_testing.html">
              <span class="en">Testing In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_admin.html">
              <span class="en">Administering In-app Billing</span></a>
          </li>
          <li><a href="../../../guide/market/billing/billing_reference.html">
              <span class="en">In-app Billing Reference</span></a>
          </li>
        </ul>
      </li>
      <li><a href="../../../guide/appendix/market-filters.html">
          <span class="en">Market Filters</span></a>
      </li>
      <li><a href="../../../guide/market/publishing/multiple-apks.html">
          <span class="en">Multiple APK Support</span></a>
      </li>
    </ul>
  </li>


  <li>
    <h2><span class="en">Developing</span>
               <span class="de" style="display:none">Entwicklung</span>
               <span class="es" style="display:none">Desarrollo</span>
               <span class="fr" style="display:none">Développement</span>
               <span class="it" style="display:none">Sviluppo</span>
               <span class="ja" style="display:none">開発</span>
               <span class="zh-CN" style="display:none">开发</span>
               <span class="zh-TW" style="display:none">開發</span>
    </h2>
    <ul>
  <!--<li><a href="">Developing for Android</a></li>
      signing, upgrading, selecting a package name, select device profile, touch, trackball, dpad available, etc. -->
      <li>
        <a href="../../../guide/developing/index.html">
        <span class="en">Introduction</span></a>
      </li>

      <li class="toggle-list">
        <div>
           <a href="../../../guide/developing/devices/index.html">
                <span class="en">Managing Virtual Devices</span>
            </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/devices/managing-avds.html">
              <span class="en">With AVD Manager</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/devices/managing-avds-cmdline.html">
              <span class="en">From the Command Line</span>
            </a>
          </li>
          <li>
           <a href="../../../guide/developing/devices/emulator.html">
                <span class="en">Using the Android Emulator</span>
            </a>
          </li>
        </ul>
      </li>
      <li>
        <a href="../../../guide/developing/device.html">
          <span class="en">Using Hardware Devices</span>
        </a>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/projects/index.html">
            <span class="en">Managing Projects</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/projects/projects-eclipse.html">
              <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/projects/projects-cmdline.html">
                <span class="en">From the Command Line</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/building/index.html">
            <span class="en">Building and Running</span>
          </a>
        </div>
        <ul>
          <li><a href="../../../guide/developing/building/building-eclipse.html">
            <span class="en">From Eclipse with ADT</span>
          </a></li>
          <li><a href="../../../guide/developing/building/building-cmdline.html">
            <span class="en">From the Command Line</span></a></li>
        </ul>
      </li>

      <li class="toggle-list">
        <div>
          <a href="../../../guide/developing/debugging/index.html">
            <span class="en">Debugging</span>
          </a>
        </div>
        <ul>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects.html">
                <span class="en">From Eclipse with ADT</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-projects-cmdline.html">
                <span class="en">From Other IDEs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/ddms.html">
              <span class="en">Using DDMS</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-log.html">
                <span class="en">Reading and Writing Logs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-ui.html">
                <span class="en">Debugging and Profiling UIs</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-tracing.html">
                <span class="en">Profiling with Traceview and dmtracedump</span>
            </a>
          </li>
          <li>
            <a href="../../../guide/developing/debugging/debugging-devtools.html">
                <span class="en">Using the Dev Tools App</span>
            </a>
          </li>
        </ul>
      </li>

      <li class="toggle-list">
           <div>
                <a href="../../../guide/developing/testing/index.html">
                   <span class="en">Testing</span>
               </a>
           </div>
           <ul>
              <li>
                <a href="../../../guide/developing/testing/testing_eclipse.html">
                  <span class="en">From Eclipse with ADT</span>
                </a>
              </li>

              <li>
                <a href="../../../guide/developing/testing/testing_otheride.html">
                  <span class="en">From Other IDEs</span>
                </a>
              </li>
           </ul>
         </li>

         <li class="toggle-list">
        <div><a href="../../../guide/developing/tools/index.html">
            <span class="en">Tools</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/developing/tools/adb.html">adb</a></li>
          <li><a href="../../../guide/developing/tools/adt.html">ADT</a></li>
          <li><a href="../../../guide/developing/tools/android.html">android</a></li>
          <li><a href="../../../guide/developing/tools/bmgr.html">bmgr</a>
          <li><a href="../../../guide/developing/tools/dmtracedump.html">dmtracedump</a></li>
          <li><a href="../../../guide/developing/tools/draw9patch.html">Draw
          9-Patch</a></li>
          <li><a href="../../../guide/developing/tools/emulator.html">Emulator</a></li>
          <li><a href="../../../guide/developing/tools/etc1tool.html">etc1tool</a></li>
          <li><a href="../../../guide/developing/tools/hierarchy-viewer.html">Hierarchy Viewer</a></li>
          <li><a href="../../../guide/developing/tools/hprof-conv.html">hprof-conv</a></li>
          <li><a href="../../../guide/developing/tools/layoutopt.html">layoutopt</a></li>
          <li><a href="../../../guide/developing/tools/logcat.html">logcat</a></li>
          <li><a href="../../../guide/developing/tools/mksdcard.html">mksdcard</a></li>
          <li><a href="../../../guide/developing/tools/monkey.html">Monkey</a></li>
          <li class="toggle-list">
            <div><a href="../../../guide/developing/tools/monkeyrunner_concepts.html">
              <span class="en">monkeyrunner</span>
            </a></div>
            <ul>
              <li><a href="../../../guide/developing/tools/MonkeyDevice.html">
                <span class="en">MonkeyDevice</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyImage.html">
                <span class="en">MonkeyImage</span>
                </a></li>
              <li><a href="../../../guide/developing/tools/MonkeyRunner.html">
                <span class="en">MonkeyRunner</span>
                </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/developing/tools/proguard.html">ProGuard</a></li>
          <li><a href="../../../guide/developing/tools/adb.html#sqlite">sqlite3</a></li>
          <li><a href="../../../guide/developing/tools/traceview.html">Traceview</a></li>
          <li><a href="../../../guide/developing/tools/zipalign.html">zipalign</a></li>
        </ul>
      </li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Publishing</span>
        <span class="de" style="display:none">Veröffentlichung</span>
        <span class="es" style="display:none">Publicación</span>
        <span class="fr" style="display:none">Publication</span>
        <span class="it" style="display:none">Pubblicazione</span>
        <span class="ja" style="display:none">公開</span>
        <span class="zh-CN" style="display:none">发布</span>
        <span class="zh-TW" style="display:none">發佈</span>
    </h2>
    <ul>
      <li><a href="../../../guide/publishing/app-signing.html">
            <span class="en">Signing Your Applications</span>
            <span class="de" style="display:none">Signieren Ihrer Anwendungen</span>
            <span class="es" style="display:none">Firma de aplicaciones</span>
            <span class="fr" style="display:none">Attribution de votre signature <br />à vos applications</span>
            <span class="it" style="display:none">Firma delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションへの署名</span>
            <span class="zh-CN" style="display:none">应用程序签名</span>
            <span class="zh-TW" style="display:none">簽署應用程式</span>
          </a></li>
      <li><a href="../../../guide/publishing/versioning.html">
            <span class="en">Versioning Your Applications</span>
            <span class="de" style="display:none">Versionsverwaltung für Ihre <br />Anwendungen</span>
            <span class="es" style="display:none">Versiones de las aplicaciones</span>
            <span class="fr" style="display:none">Attribution d'une version à vos applications</span>
            <span class="it" style="display:none">Controllo versioni delle applicazioni</span>
            <span class="ja" style="display:none">アプリケーションのバージョニング</span>
            <span class="zh-CN" style="display:none">应用程序版本控制</span>
            <span class="zh-TW" style="display:none">應用程式版本設定</span>
          </a></li>
      <li><a href="../../../guide/publishing/preparing.html">
            <span class="en">Preparing to Publish</span>
            <span class="de" style="display:none">Vorbereitung auf die Veröffentlichung</span>
            <span class="es" style="display:none">Publicación de aplicaciones</span>
            <span class="fr" style="display:none">Préparation à la publication</span>
            <span class="it" style="display:none">Preparativi per la pubblicazione</span>
            <span class="ja" style="display:none">公開の準備</span>
            <span class="zh-CN" style="display:none">准备发布</span>
            <span class="zh-TW" style="display:none">準備發佈</span>
          </a></li>
      <li><a href="../../../guide/publishing/publishing.html">
            <span class="en">Publishing on Android Market</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Best Practices</span>
               <span class="de" style="display:none">Bewährte Verfahren</span>
               <span class="es" style="display:none">Prácticas recomendadas</span>
               <span class="fr" style="display:none">Meilleures pratiques</span>
               <span class="it" style="display:none">Best practice</span>
               <span class="ja" style="display:none">ベスト プラクティス</span>
               <span class="zh-CN" style="display:none">最佳实践</span>
               <span class="zh-TW" style="display:none">最佳實務</span>
    </h2>
    <ul>
      <li><a href="../../../guide/practices/compatibility.html">
            <span class="en">Compatibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/screens_support.html">
          <span class="en">Supporting Multiple Screens</span>
        </a></div>
        <ul>
          <li><a href="../../../guide/practices/screens-distribution.html">
            <span class="en">Distributing to Specific Screens</span>
          </a></li>
          <li><a href="../../../guide/practices/screen-compat-mode.html">
            <span class="en">Screen Compatibility Mode</span>
          </a></li>
          <li><a href="../../../guide/practices/screens-support-1.5.html">
            <span class="en">Strategies for Android 1.5</span>
          </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/optimizing-for-3.0.html">
            <span class="en">Optimizing Apps for Android 3.0</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/ui_guidelines/index.html">
               <span class="en">UI Guidelines</span>
             </a></div>
        <ul>
          <li class="toggle-list">
            <div><a href="../../../guide/practices/ui_guidelines/icon_design.html">
                   <span class="en">Icon Design <span class="new">updated</span></span>
                 </a></div>
            <ul>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_launcher.html">
                    <span class="en">Launcher Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_menu.html">
                    <span class="en">Menu Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_action_bar.html">
                    <span class="en">Action Bar Icons <span class="new">new!</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_status_bar.html">
                    <span class="en">Status Bar Icons <span class="new">updated</span></span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_tab.html">
                    <span class="en">Tab Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_dialog.html">
                    <span class="en">Dialog Icons</span>
                  </a></li>
              <li><a href="../../../guide/practices/ui_guidelines/icon_design_list.html">
                    <span class="en">List View Icons</span>
                  </a></li>
            </ul>
          </li>
          <li><a href="../../../guide/practices/ui_guidelines/widget_design.html">
                <span class="en">App Widget Design <span class="new">updated</span></span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/activity_task_design.html">
                <span class="en">Activity and Task Design</span>
              </a></li>
          <li><a href="../../../guide/practices/ui_guidelines/menu_design.html">
                <span class="en">Menu Design</span>
              </a></li>
        </ul>
      </li>
      </ul>
      <ul>
      <li><a href="../../../guide/practices/design/accessibility.html">
            <span class="en">Designing for Accessibility</span>
          </a></li>
      <li class="toggle-list">
        <div><a href="../../../guide/practices/design/performance.html">
            <span class="en">Designing for Performance</span>
          </a></div>
        <ul>
          <li><a href="../../../guide/practices/design/jni.html">
                <span class="en">JNI Tips</span>
              </a></li>
        </ul>
      </li>
      <li><a href="../../../guide/practices/design/responsiveness.html">
            <span class="en">Designing for Responsiveness</span>
          </a></li>
      <li><a href="../../../guide/practices/design/seamlessness.html">
            <span class="en">Designing for Seamlessness</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Web Applications</span>
    </h2>
    <ul>
      <li><a href="../../../guide/webapps/index.html">
            <span class="en">Web Apps Overview</span>
          </a></li>
      <li><a href="../../../guide/webapps/targeting.html">
            <span class="en">Targeting Screens from Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/webview.html">
            <span class="en">Building Web Apps in WebView</span>
          </a></li>
      <li><a href="../../../guide/webapps/debugging.html">
            <span class="en">Debugging Web Apps</span>
          </a></li>
      <li><a href="../../../guide/webapps/best-practices.html">
            <span class="en">Best Practices for Web Apps</span>
          </a></li>
    </ul>
  </li>

  <li>
    <h2><span class="en">Appendix</span>
               <span class="de" style="display:none">Anhang</span>
               <span class="es" style="display:none">Apéndice</span>
               <span class="fr" style="display:none">Annexes</span>
               <span class="it" style="display:none">Appendice</span>
               <span class="ja" style="display:none">付録</span>
               <span class="zh-CN" style="display:none">附录</span>
               <span class="zh-TW" style="display:none">附錄</span>
    </h2>
    <ul>
      <li><a href="../../../guide/appendix/api-levels.html">
            <span class="en">Android API Levels</span>
          </a></li>
      <li><a href="../../../guide/appendix/install-location.html">
            <span class="en">App Install Location</span>
          </a></li>
      <li><a href="../../../guide/appendix/media-formats.html">
            <span class="en">Supported Media Formats <span class="new">updated</span></span>
          </a></li>
      <li><a href="../../../guide/appendix/g-app-intents.html">
            <span class="en">Intents List: Google Apps</span>
          </a></li>
      <li><a href="../../../guide/developing/tools/aidl.html">AIDL</a></li>
      <li><a href="../../../guide/appendix/glossary.html">
            <span class="en">Glossary</span>
          </a></li>
    </ul>
  </li>

</ul>

<script type="text/javascript">
<!--
    buildToggleLists();
    changeNavLang(getLangPref());
//-->
</script>

      </div>
    </div> <!-- end side-nav -->
    <script>
      addLoadEvent(function() {
        scrollIntoView("devdoc-nav");
        });
    </script>




<div class="g-unit" id="doc-content"><a name="top"></a>

<div id="jd-header" class="guide-header">
  <span class="crumb">
    &nbsp;
    
  </span>
<h1>Activities 活动</h1>
</div>

  <div id="jd-content">

    <div class="jd-descr">
    <div id="qv-wrapper">
<div id="qv">
<h2>Quickview</h2>
<ul>
  <li>An activity provides a user interface for a single screen in your application</li>
  <li>Activities can move into the background and then be resumed with their state restored</li>
</ul>

<h2>In this document</h2>
<ol>
  <li><a href="#Creating">Creating an Activity</a>
    <ol>
      <li><a href="#UI">Implementing a user interface</a></li>
      <li><a href="#Declaring">Declaring the activity in the manifest</a></li>
    </ol>
  </li>
  <li><a href="#StartingAnActivity">Starting an Activity</a>
    <ol>
      <li><a href="#StartingAnActivityForResult">Starting an Activity for a Result</a></li>
    </ol>
  </li>
  <li><a href="#Lifecycle">Managing the Activity Lifecycle</a>
    <ol>
      <li><a href="#ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks</a></li>
      <li><a href="#SavingActivityState">Saving activity state</a></li>
      <li><a href="#ConfigurationChanges">Handling configuration changes</a></li>
      <li><a href="#CoordinatingActivities">Coordinating activities</a></li>
    </ol>
  </li>
</ol>

<h2>Key classes</h2>
<ol>
  <li><code><a href="../../../reference/android/app/Activity.html">Activity</a></code></li>
</ol>

<h2>See also</h2>
<ol>
  <li><a href="../../../resources/tutorials/hello-world.html">Hello World Tutorial</a></li>
  <li><a href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
Stack</a></li>
</ol>

</div>
</div>



<p>An <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> is an application component that provides a screen with which
users can interact in order to do something, such as dial the phone, take a photo, send an email, or
view a map. Each activity is given a window in which to draw its user interface. The window
typically fills the screen, but may be smaller than the screen and float on top of other
windows.</p>
<p>Activity提供一个用户能够交互的界面，比如拨打电话，照相，发邮件，或者浏览地图。每个activity都是一个用户可拖拽的特定窗口。这个窗口通常填满整个屏幕，也有可能小于屏幕，然后浮动在其他窗口上。</p>

<p> An application usually consists of multiple activities that are loosely bound
to each other. Typically, one activity in an application is specified as the "main" activity, which
is presented to the user when launching the application for the first time. Each
activity can then start another activity in order to perform different actions. Each time a new
activity starts, the previous activity is stopped, but the system preserves the activity
in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and
takes user focus. The back stack abides to the basic "last in, first out" queue mechanism,
so, when the user is done with the current activity and presses the BACK key, it
is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is
discussed more in the <a href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">Tasks
and Back Stack</a> document.)</p>
<p>一个程序通常由很多activity组成，他们彼此的约束很宽松。通常的，一个activity被指定为‘main’，那么程序第一次运行的时候会执行它。每个activity可以启动其他的activity。每次启动新的activity的时候，前面的activity就会被停止，系统会保存他们在堆栈中。当一个新的activity开始，它就被放入到堆栈的顶部，然后展示给用户。这个堆栈遵守“后进先出”的队列原理。所以，当用户完成当前activity然后点击返回按钮的时候，这个activity从堆栈中被取出，并销毁。然后前面activity会被恢复。</p>

<p>When an activity is stopped because a new activity starts, it is notified of this change in state
through the activity's lifecycle callback methods.
There are several callback methods that an activity might receive, due to a change in its
state&mdash;whether the system is creating it, stopping it, resuming it, or destroying it&mdash;and
each callback provides you the opportunity to perform specific work that's
appropriate to that state change. For instance, when stopped, your activity should release any
large objects, such as network or database connections. When the activity resumes, you can
reacquire the necessary resources and resume actions that were interrupted. These state transitions
are all part of the activity lifecycle.</p>
<p>当一个activity因为一个新的activity的启动而被停止时，activity的生命周期callback方法会通知这个activity这个改变。一个activity会接收到很多callback方法。像系统创建它，停止它，恢复它，或者销毁它。并且，每个callback提供给你机会去执行特定的工作。比如，停止activity的时候，你必须释放一些大的对象，像网络或者数据库连接。当activity恢复的时候，你可以请求必须的资源并恢复被中断的动作。</p>

<p>The rest of this document discusses the basics of how to build and use an activity,
including a complete discussion of how the activity lifecycle works, so you can properly manage
the transition between various activity states.</p>
<p>剩下的文档讨论建立和使用activity的基本方法。包括activity工作的周期。所以你可以适当的管理不同activity状态的改变。</p>



<h2 id="Creating">Creating an Activity 创建一个活动</h2>

<p>To create an activity, you must create a subclass of <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> (or
an existing subclass of it). In your subclass, you need to implement callback methods that the
system calls when the activity transitions between various states of its lifecycle, such as when
the activity is being created, stopped, resumed, or destroyed. The two most important callback
methods are:</p>
<p>要创建一个活动，你必须创建一个Activity的子类。在你的子类中，当活动的状态改变时，你必须实现callback方法。下面是比较重要的两个callback方法：</p>

<dl>
  <dt><code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code></dt>
  <dd>You must implement this method. The system calls this when creating your
    activity. Within your implementation, you should initialize the essential components of your
activity.
    Most importantly, this is where you must call <code><a href="../../../reference/android/app/Activity.html#setContentView(android.view.View)">setContentView()</a></code> to define the layout for the activity's user interface.
	<p>这个方法是必须实现的，活动创建时系统会调用这个方法。在你的代码实现里面，你需要初始化活动最基本的组件。最重要的是，这是你调用setContentView()去定义活动界面布局的地方。</p></dd>
  <dt><code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code></dt>
  <dd>The system calls this method as the first indication that the user is leaving your
activity (though it does not always mean the activity is being destroyed). This is usually where you
should commit any changes that should be persisted beyond the current user session (because
the user might not come back).
<p>系统调用这个方法告诉你用户已经离开了这个活动。</p></dd>
</dl>

<p>There are several other lifecycle callback methods that you should use in order to provide a
fluid user experience between activities and handle unexpected interuptions that cause your activity
to be stopped and even destroyed. All of the lifecycle callback methods are discussed later, in
the section about <a href="#Lifecycle">Managing the Activity Lifecycle</a>.</p>
<p>还有很多callback方法你可以使用，为了给用户提供流畅的用户体验。</p>


<h3 id="UI">Implementing a user interface 实现一个界面</h3>

<p> The user interface for an activity is provided by a hierarchy of views&mdash;objects derived
from the <code><a href="../../../reference/android/view/View.html">View</a></code> class.  Each view controls a particular rectangular space
within the activity's window and can respond to user interaction. For example, a view might be a
button that initiates an action when the user touches it.</p>
<p>View按照不同的等级提供活动界面，每个view控制一个特别矩形区域，这个区域能够响应用户操作。比如，一个view可以是一个按钮，用户触碰它的时候会开始一个行为。</p>

<p>Android provides a number of ready-made views that you can use to design and organize your
layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such
as a button, text field, checkbox, or just an image. "Layouts" are views derived from <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> that provide a unique layout model for its child views, such as a linear
layout, a grid layout, or relative layout. You can also subclass the <code><a href="../../../reference/android/view/View.html">View</a></code> and
<code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> classes (or existing subclasses) to create your own widgets and
layouts and apply them to your activity layout.</p>
<p>Android提供很多已经设定好的view，你可以使用它们去设计和组织你的布局。"Widgets"是提供视觉效果的元素，像按钮，文本框，选择框，或者图片等。"Layouts"通过ViewGroup提供一个独特的布局模式。比如线性布局，网格布局，相对布局。你也可以扩展View和ViewGroup类去建立自己的widgets 和layouts。</p>

<p>The most common way to define a layout using views is with an XML layout file saved in your
application resources. This way, you can maintain the design of your user interface separately from
the source code that defines the activity's behavior. You can set the layout as the UI for your
activity with <code><a href="../../../reference/android/app/Activity.html#setContentView(int)">setContentView()</a></code>, passing the
resource ID for the layout. However, you can also create new <code><a href="../../../reference/android/view/View.html">View</a></code>s in your
activity code and build a view hierarchy by inserting new <code><a href="../../../reference/android/view/View.html">View</a></code>s into a <code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code>, then use that layout by passing the root
<code><a href="../../../reference/android/view/ViewGroup.html">ViewGroup</a></code> to <code><a href="../../../reference/android/app/Activity.html#setContentView(android.view.View)">setContentView()</a></code>.</p>
<p>最普通的定义布局的方法是在资源文件中建立XML布局文件。实现代码和界面设计的分离。你可以使用setContentView()设置UI。然而，你也可以在代码中建立新的View，并且建立一个等级，把新的View插入到ViewGroup中。</p>

<p>For information about creating a user interface, see the <a
href="../../../guide/topics/ui/index.html">User Interface</a> documentation.</p>



<h3 id="Declaring">Declaring the activity in the manifest 在清单文件中声明activity</h3>

<p>You must declare your activity in the manifest file in order for it to
be accessible to the system. To declare your activity, open your manifest file and add an <a
href="../../../guide/topics/manifest/activity-element.html"><code>&lt;activity&gt;</code></a> element
as a child of the <a
href="../../../guide/topics/manifest/application-element.html"><code>&lt;application&gt;</code></a>
element. For example:</p>
<p>你必须在清单文件中定义你的activity以便系统可以认识。像下面这个定义：</p>

<pre>
&lt;manifest ... &gt;
  &lt;application ... &gt;
      &lt;activity android:name=".ExampleActivity" /&gt;
      ...
  &lt;/application ... &gt;
  ...
&lt;/manifest &gt;
</pre>

<p>There are several other attributes that you can include in this element, to define properties
such as the label for the activity, an icon for the activity, or a theme to style the activity's
UI. The <a href="../../../guide/topics/manifest/activity-element.html#nm"><code>android:name</code></a>
attribute is the only required attribute&mdash;it specifies the class name of the activity. Once
you publish your application, you should not change this name, because if you do, you might break
some functionality, such as application shortcuts (read the blog post, <a
href="http://android-developers.blogspot.com/2011/06/things-that-cannot-change.html">Things
That Cannot Change</a>).</p>
<p>在这个元素中还可以包含其他很多属性，比如activity的文本标记，图标，样式模板。<code>android:name</code>属性是必须的。它是activity的类名。一旦发布了你的程序，这个名称就不能改变了。如果你改变的话会破坏很多功能。</p>

<p>See the <a
href="../../../guide/topics/manifest/activity-element.html"><code>&lt;activity&gt;</code></a> element
reference for more information about declaring your activity in the manifest.</p>


<h4>Using intent filters 使用过滤器</h4>

<p>An <a href="../../../guide/topics/manifest/activity-element.html"><code>&lt;activity&gt;</code></a> element can also specify various intent filters&mdash;using the <a
href="../../../guide/topics/manifest/intent-filter-element.html"><code>&lt;intent-filter&gt;</code></a> element&mdash;in order to declare how other application components may
activate it.</p>
<p><code>&lt;activity&gt;</code>元素可以指定不同的过滤器&mdash;使用<code>&lt;intent-filter&gt;</code>元素&mdash;为了定义其他组件怎么激活它。</p>

<p>When you create a new application using the Android SDK tools, the stub activity
that's created for you automatically includes an intent filter that declares the activity
responds to the "main" action and should be placed in the "launcher" category. The intent filter
looks like this:</p>
<p>当你使用SDK工具建立一个程序的时候，会自动生成一个过滤器，并定义了一个activity响应main行为。它放在launcher分类下。像这样：</p>

<pre>
&lt;activity android:name=".ExampleActivity" android:icon="@drawable/app_icon"&gt;
    &lt;intent-filter&gt;
        &lt;action android:name="android.intent.action.MAIN" /&gt;
        &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
    &lt;/intent-filter&gt;
&lt;/activity&gt;
</pre>

<p>The <a href="../../../guide/topics/manifest/action-element.html"><code>&lt;action&gt;</code></a> element specifies that this is the "main" entry point to the application. The <a
href="../../../guide/topics/manifest/category-element.html"><code>&lt;category&gt;</code></a> element specifies that this activity should be listed in the
system's application launcher (to allow users to launch this activity).</p>
<p><code>&lt;action&gt;</code>定义了main是程序的进入点。<code>&lt;category&gt;</code>指定activity必须被列在系统程序发射台中。</p>

<p>If you intend for your application to be self-contained and not allow other applications to
activate its activities, then you don't need any other intent filters. Only one activity should
have the "main" action and "launcher" category, as in the previous example. Activities that
you don't want to make available to other applications should have no intent filters and you can
start them yourself using explicit intents (as discussed in the following section).</p>
<p>如果你打算让你的程序不允许其他程序激活它的activity，你就不需要任何的intent filters。</p>

<p>However, if you want your activity to respond to implicit intents that are delivered from
other applications (and your own), then you must define additional intent filters for your
activity. For each type of intent to which you want to respond, you must include an <a
href="../../../guide/topics/manifest/intent-filter-element.html"><code>&lt;intent-filter&gt;</code></a> that includes an
<a href="../../../guide/topics/manifest/action-element.html"><code>&lt;action&gt;</code></a> element and, optionally, a <a
href="../../../guide/topics/manifest/category-element.html"><code>&lt;category&gt;</code></a> element and/or a <a
href="../../../guide/topics/manifest/data-element.html"><code>&lt;data&gt;</code></a> element. These elements specify the type of intent to which your activity can
respond.</p>
<p>然而，如果你希望activity响应暗示的请求。你必须定义附加的intent filter。</p>

<p>For more information about how your activities can respond to intents, see the <a
href="../../../guide/topics/intents/intents-filters.html">Intents and Intent Filters</a>
document.</p>



<h2 id="StartingAnActivity">Starting an Activity 开始一个activity</h2>

<p>You can start another activity by calling <code><a href="../../../reference/android/app/Activity.html#startActivity(android.content.Intent)">startActivity()</a></code>, passing it an <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> that describes the activity you
  want to start. The intent specifies either the exact activity you want to start or describes the
  type of action you want to perform (and the system selects the appropriate activity for you,
which
  can even be from a different application). An intent can also carry small amounts of data to be
  used by the activity that is started.</p>
<p>可以通过调用<code><a href="../../../reference/android/app/Activity.html#startActivity(android.content.Intent)">startActivity()</a></code>开始另外的activity，通过Intent描述哪个activity是你想启动的。一个intent也可以传递少量的数据到被启动的activity中。</p>

<p>When working within your own application, you'll often need to simply launch a known activity.
 You can do so by creating an intent that explicitly defines the activity you want to start,
using the class name. For example, here's how one activity starts another activity named <code>SignInActivity</code>:</p>
<p>在你自己的程序中，你可能会经常会运行一个已知的activity。你可以使用类名明确的指定一个activity去启动。比如，下面的程序实现了一个activity怎么启动另外一个名为<code>SignInActivity</code>的activity。</p>

<pre>
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
</pre>

<p>However, your application might also want to perform some action, such as send an email, text
  message, or status update, using data from your activity. In this case, your application might
 not have its own activities to perform such actions, so you can instead leverage the activities
  provided by other applications on the device, which can perform the actions for you. This is where
intents are really valuable&mdash;you can create an intent that describes an action you want to
perform and the system
  launches the appropriate activity from another application. If there are
  multiple activities that can handle the intent, then the user can select which one to use. For
  example, if you want to allow the user to send an email message, you can create the
  following intent:</p>
<p>你的程序可能也想运行其他行为，比如发邮件，发短信，或者更新状态。在这种情况下，你的程序没有自己的activity去实现这些功能，因此你可以设备上的其他程序代替实现这个功能。你可以定义一个intent，然后系统对于的调用给你activity。如果有多个对应的功能，系统会提示用户选择。下面是调用发邮件的例子：</p>

<pre>
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);
</pre>

<p>The <code><a href="../../../reference/android/content/Intent.html#EXTRA_EMAIL">EXTRA_EMAIL</a></code> extra added to the intent is a string array of
  email addresses to which the email should be sent. When an email application responds to this
  intent, it reads the string array provided in the extra and places them in the "to" field of the
  email composition form. In this situation, the email application's activity starts and when the
  user is done, your activity resumes.</p>
<p><code><a href="../../../reference/android/content/Intent.html#EXTRA_EMAIL">EXTRA_EMAIL</a></code>是一个邮件地址的数组。当一个邮件程序响应这个intent的时候，它会读取这个数组，然后显示到收件人的区域，在这种情况下，邮件activity启动，发送完成后，你的activity会恢复。</p>



<h3 id="StartingAnActivityForResult">Starting an activity for a result 为结果启动一个activity</h3>

<p>Sometimes, you might want to receive a result from the activity that you start. In that case,
  start the activity by calling <code><a href="../../../reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)">startActivityForResult()</a></code> (instead of <code><a href="../../../reference/android/app/Activity.html#startActivity(android.content.Intent)">startActivity()</a></code>). To then receive the result from the subsequent
activity, implement the <code><a href="../../../reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent)">onActivityResult()</a></code> callback
  method. When the subsequent activity is done, it returns a result in an <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> to your <code><a href="../../../reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent)">onActivityResult()</a></code>
method.</p>
<p>有时候你想从你启动的activity中接收一个结果。这种情况下，使用startActivityForResult()启动一个activity,然后通过onActivityResult()取得结果。当后来启动的activity结束后，会返回一个结果在Intent中。</p>

<p>For example, perhaps you want the user to pick one of their contacts, so your activity can
do something with the information in that contact. Here's how you can create such an intent and
handle the result:</p>
<p>比如你希望用户挑选一个他们的联系人，下面的代码说明了你怎么建立一个intent然后操作结果。</p>

<pre>
private void pickContact() {
    // Create an intent to "pick" a contact, as defined by the content provider URI
    Intent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
    startActivityForResult(intent, PICK_CONTACT_REQUEST);
}

&#64;Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // If the request went well (OK) and the request was PICK_CONTACT_REQUEST
    if (resultCode == Activity.RESULT_OK &amp;&amp; requestCode == PICK_CONTACT_REQUEST) {
        // Perform a query to the contact's content provider for the contact's name
        Cursor cursor = getContentResolver().query(data.getData(),
        new String[] {Contacts.DISPLAY_NAME}, null, null, null);
        if (cursor.moveToFirst()) { // True if the cursor is not empty
            int columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
            String name = cursor.getString(columnIndex);
            // Do something with the selected contact's name...
        }
    }
}
</pre>

<p>This example shows the basic logic you should use in your <code><a href="../../../reference/android/app/Activity.html#onActivityResult(int, int, android.content.Intent)">onActivityResult()</a></code> method in order to handle an
activity result. The first condition checks whether the request was successful&mdash;if it was, then
the <code>resultCode</code> will be <code><a href="../../../reference/android/app/Activity.html#RESULT_OK">RESULT_OK</a></code>&mdash;and whether the request
to which this result is responding is known&mdash;in this case, the <code>requestCode</code> matches the
second parameter sent with <code><a href="../../../reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)">startActivityForResult()</a></code>. From there, the code handles the activity result by querying the
data returned in an <code><a href="../../../reference/android/content/Intent.html">Intent</a></code> (the <code>data</code> parameter).</p>
<p>例子中我们先确认请求是否成功，如成功<code>resultCode</code>会是RESULT_OK，requestCode对应startActivityForResult()中的第二个参数。activity返回的结果保存在Intent中。</p>

<p>What happens is, a <code><a href="../../../reference/android/content/ContentResolver.html">ContentResolver</a></code> performs a query against a content provider, which returns a
<code><a href="../../../reference/android/database/Cursor.html">Cursor</a></code> that allows the queried data to be read. For more information, see
the <a
href="../../../guide/topics/providers/content-providers.html">Content Providers</a> document.</p>

<p>For more information about using intents, see the <a
href="../../../guide/topics/intents/intents-filters.html">Intents and Intent
Filters</a> document.</p>


<h2 id="ShuttingDown">Shutting Down an Activity 停止一个activity</h2>

<p>You can shut down an activity by calling its <code><a href="../../../reference/android/app/Activity.html#finish()">finish()</a></code> method. You can also shut down a separate activity that you previously started by calling
<code><a href="../../../reference/android/app/Activity.html#finishActivity(int)">finishActivity()</a></code>.</p>
<p>finish()方法能够停止一个activity。你也可以通过finishActivity()停止一个你先前启动的activity。</p>

<p class="note"><strong>Note:</strong> In most cases, you should not explicitly finish an activity
using these methods. As discussed in the following section about the activity lifecycle, the
Android system manages the life of an activity for you, so you do not need to finish your own
activities. Calling these methods could adversely affect the expected user
experience and should only be used when you absolutely do not want the user to return to this
instance of the activity.</p>
<p class="note"><strong>Note:</strong>在大多数情况下，你不需要明确的关闭一个activity。android系统会帮助你管理activity。使用这些方法会给用户带来不利的用户体验，除非你非常的确定用户不会在使用这个activity了才使用这些方法。</p>


<h2 id="Lifecycle">Managing the Activity Lifecycle 管理activity的生命周期</h2>

<p>Managing the lifecycle of your activities by implementing callback methods is
crucial to developing a strong
and flexible application. The lifecycle of an activity is directly affected by its association with
other activities, its task and back stack.</p>
<p>执行callback方法去管理activity的生命周期是开发健壮和灵活程序的关键。一个activity的生命周期被相关的其他activity直接影响。这就是任务和堆栈。</p>

<p>An activity can exist in essentially three states:</p>
<p>一个activity本质上只有3个状态</p>

<dl>
  <dt><i>Resumed</i></dt>
    <dd>The activity is in the foreground of the screen and has user focus. (This state is
also sometimes referred to as "running".)
<p>正运行在屏幕前，并且有用户焦点。</p></dd>

  <dt><i>Paused</i></dt>
    <dd>Another activity is in the foreground and has focus, but this one is still visible. That is,
another activity is visible on top of this one and that activity is partially transparent or doesn't
cover the entire screen. A paused activity is completely alive (the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code>
object is retained in memory, it maintains all state and member information, and remains attached to
the window manager), but can be killed by the system in extremely low memory situations.
<p>部分可见，或者半透明状态，而且是可用的。一个paused activity是完全运行在内存中的Activity对象。在系统及其缺乏内存的时候会被系统杀掉。</p></dd>

  <dt><i>Stopped</i></dt>
    <dd>The activity is completely obscured by another activity (the activity is now in the
"background"). A stopped activity is also still alive (the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code>
object is retained in memory, it maintains all state and member information, but is <em>not</em>
attached to the window manager). However, it is no longer visible to the user and it
can be killed by the system when memory is needed elsewhere.
<p>相对于其他activity来说，这个状态是完全模糊的。他也会被保存在内存中。系统任何地方需要内存的情况下都可用杀掉它。</p></dd>
</dl>

<p>If an activity is paused or stopped, the system can drop it from memory either by asking it to
finish (calling its <code><a href="../../../reference/android/app/Activity.html#finish()">finish()</a></code> method), or simply killing its
process.  When the activity is opened again (after being finished or killed), it must be created all
over.</p>
<p>如果一个activity是暂停或者停止状态，系统可用通过finish方法或者停止进程的方法把它们移出内存。如果需要重新启动，那么就需要从新启动所有的资源。</p>


<h3 id="ImplementingLifecycleCallbacks">Implementing the lifecycle callbacks 执行生命周期方法</h3>

<p>When an activity transitions into and out of the different states described above, it is notified
through various callback methods. All of the callback methods are hooks that you
can override to do appropriate work when the state of your activity changes. The following skeleton
activity includes each of the fundamental lifecycle methods:</p>
<p>有很多不同的方法可以改变activity的状态，下面是代码示例：</p>

<pre>
public class ExampleActivity extends Activity {
    &#64;Override
    public void <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate</a></code>(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // The activity is being created.
    }
    &#64;Override
    protected void <code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code> {
        super.onStart();
        // The activity is about to become visible.
    }
    &#64;Override
    protected void <code><a href="../../../reference/android/app/Activity.html#onResume()">onResume()</a></code> {
        super.onResume();
        // The activity has become visible (it is now "resumed").
    }
    &#64;Override
    protected void <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> {
        super.onPause();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    &#64;Override
    protected void <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> {
        super.onStop();
        // The activity is no longer visible (it is now "stopped")
    }
    &#64;Override
    protected void <code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code> {
        super.onDestroy();
        // The activity is about to be destroyed.
    }
}
</pre>

<p class="note"><strong>Note:</strong> Your implementation of these lifecycle methods must
always call the superclass implementation before doing any work, as shown in the examples above.</p>
<p class="note"><strong>Note:</strong>执行这些方法需要先调用父类的方法。</p>

<p>Taken together, these methods define the entire lifecycle of an activity. By implementing these
methods, you can monitor three nested loops in the activity lifecycle: </p>
<p>3种循环方式：</p>

<ul>
<li>The <b>entire lifetime</b> of an activity happens between the call to <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> and the call to <code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code>. Your activity should perform setup of
"global" state (such as defining layout) in <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code>, and
release all remaining resources in <code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code>. For example, if your
activity has a thread running in the background to download data from the network, it might create
that thread in <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> and then stop the thread in <code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code>.
<p><b>完整周期</b>开始于onCreate()，结束于onDestroy()并释放所有资源。</p></li>

<li><p>The <b>visible lifetime</b> of an activity happens between the call to <code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code> and the call to <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code>. During this time, the user can see the activity
on-screen and interact with it. For example, <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> is called
when a new activity starts and this one is no longer visible. Between these two methods, you can
maintain resources that are needed to show the activity to the user. For example, you can register a
<code><a href="../../../reference/android/content/BroadcastReceiver.html">BroadcastReceiver</a></code> in <code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code> to monitor changes that impact your UI, and unregister
it in <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> when the user can no longer see what you are
displaying. The system might call <code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code> and <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> multiple times during the entire lifetime of the activity, as
the activity alternates between being visible and hidden to the user.</p>
<p><b>可见周期</b>从onStart()开始到onStop()，这个时间里，用户可以在屏幕上看到，并且进行交互。例如，你为了启动一个新的使用时间不长的activity而使用onStop()去停止当前activity的时，你可以保留用户使用的资源。比如，你可以登记一个广播接收器去监听UI的变化，并且在用户很久没有使用的情况下注销这个广播接收器。在一个完整周期中可能会使用多次可见周期。</p></li>

<li><p>The <b>foreground lifetime</b> of an activity happens between the call to <code><a href="../../../reference/android/app/Activity.html#onResume()">onResume()</a></code> and the call to <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code>. During this time, the activity is in front of all other activities on screen and has
user input focus.  An activity can frequently transition in and out of the foreground&mdash;for
example, <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> is called when the device goes to sleep or
when a dialog appears. Because this state can transition often, the code in these two methods should
be fairly lightweight in order to avoid slow transitions that make the user wait.</p>
<p><b>前景周期</b>开始于onResume()结束于onPause()，在这个期间，这个activity展现在屏幕的最前方，并且享有用户焦点。比如，当设备休眠或者弹出对话框时会调用onPause()。因为这个状态会经常改变，所以这两个方法是轻量级的。</p></li>
</ul>

<p>Figure 1 illustrates these loops and the paths an activity might take between states.
The rectangles represent the callback methods you can implement to perform operations when
the activity transitions between states. <p>
<p>看图吧</p>

<img src="../../../images/activity_lifecycle.png" alt="" />
<p class="img-caption"><strong>Figure 1.</strong> The activity lifecycle.</p>

<p>The same lifecycle callback methods are listed in table 1, which describes each of the callback
methods in more detail and locates each one within the
activity's overall lifecycle, including whether the system can kill the activity after the
callback method completes.</p>
<p>看表吧</p>

<p class="table-caption"><strong>Table 1.</strong> A summary of the activity lifecycle's
callback methods.</p>

<table border="2" width="85%" frame="hsides" rules="rows">
<colgroup align="left" span="3"></colgroup>
<colgroup align="left"></colgroup>
<colgroup align="center"></colgroup>
<colgroup align="center"></colgroup>

<thead>
<tr><th colspan="3">Method</th> <th>Description</th> <th>Killable after?</th> <th>Next</th></tr>
</thead>

<tbody>
<tr>
  <td colspan="3" align="left"><code><code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code></code></td>
  <td>Called when the activity is first created.
      This is where you should do all of your normal static set up &mdash;
      create views, bind data to lists, and so on.  This method is passed
      a Bundle object containing the activity's previous state, if that
      state was captured (see <a href="#actstate">Saving Activity State</a>,
      later).
      <p>Always followed by <code>onStart()</code>.</p>
	  <p>这个方法会通过一个捆绑对象包含activity以前的状态。</p></td>
  <td align="center">No</td>
      <td align="center"><code>onStart()</code></td>
</tr>

<tr>
   <td rowspan="5" style="border-left: none; border-right: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
   <td colspan="2" align="left"><code><code><a href="../../../reference/android/app/Activity.html#onRestart()">onRestart()</a></code></code></td>
   <td>Called after the activity has been stopped, just prior to it being
       started again.
       <p>Always followed by <code>onStart()</code></p></td>
   <td align="center">No</td>
   <td align="center"><code>onStart()</code></td>
</tr>

<tr>
   <td colspan="2" align="left"><code><code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code></code></td>
   <td>Called just before the activity becomes visible to the user.
       <p>Followed by <code>onResume()</code> if the activity comes
       to the foreground, or <code>onStop()</code> if it becomes hidden.</p></td>
    <td align="center">No</td>
    <td align="center"><code>onResume()</code> <br/>or<br/> <code>onStop()</code></td>
</tr>

<tr>
   <td rowspan="2" style="border-left: none;">&nbsp;&nbsp;&nbsp;&nbsp;</td>
   <td align="left"><code><code><a href="../../../reference/android/app/Activity.html#onResume()">onResume()</a></code></code></td>
   <td>Called just before the activity starts
       interacting with the user.  At this point the activity is at
       the top of the activity stack, with user input going to it.
       <p>Always followed by <code>onPause()</code>.</p></td>
   <td align="center">No</td>
   <td align="center"><code>onPause()</code></td>
</tr>

<tr>
   <td align="left"><code><code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code></code></td>
   <td>Called when the system is about to start resuming another
       activity.  This method is typically used to commit unsaved changes to
       persistent data, stop animations and other things that may be consuming
       CPU, and so on.  It should do whatever it does very quickly, because
       the next activity will not be resumed until it returns.
       <p>Followed either by <code>onResume()</code> if the activity
       returns back to the front, or by <code>onStop()</code> if it becomes
       invisible to the user.
	   <p>系统启动其它activity的时候会调用。</p></td>
   <td align="center"><strong style="color:#800000">Yes</strong></td>
   <td align="center"><code>onResume()</code> <br/>or<br/> <code>onStop()</code></td>
</tr>

<tr>
   <td colspan="2" align="left"><code><code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code></code></td>
   <td>Called when the activity is no longer visible to the user.  This
       may happen because it is being destroyed, or because another activity
       (either an existing one or a new one) has been resumed and is covering it.
       <p>Followed either by <code>onRestart()</code> if
       the activity is coming back to interact with the user, or by
       <code>onDestroy()</code> if this activity is going away.</p></td>
   <td align="center"><strong style="color:#800000">Yes</strong></td>
   <td align="center"><code>onRestart()</code> <br/>or<br/> <code>onDestroy()</code></td>
</tr>

<tr>
   <td colspan="3" align="left"><code><code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code></code></td>
   <td>Called before the activity is destroyed.  This is the final call
       that the activity will receive.  It could be called either because the
       activity is finishing (someone called <code><code><a href="../../../reference/android/app/Activity.html#finish()">finish()</a></code></code> on it), or because the system is temporarily destroying this
       instance of the activity to save space.  You can distinguish
       between these two scenarios with the <code><code><a href="../../../reference/android/app/Activity.html#isFinishing()">isFinishing()</a></code></code> method.</td>
   <td align="center"><strong style="color:#800000">Yes</strong></td>
   <td align="center"><em>nothing</em></td>
</tr>
</tbody>
</table>

<p>The column labeled "Killable after?" indicates whether or not the system can
kill the process hosting the activity at any time <em>after the method returns</em>, without
executing another line of the activity's code.  Three methods are marked "yes": (<code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code>, <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code>, and <code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code>). Because <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> is the first
of the three, once the activity is created, <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> is the
last method that's guaranteed to be called before the process <em>can</em> be killed&mdash;if
the system must recover memory in an emergency, then <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> and <code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code> might
not be called. Therefore, you should use <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> to write
crucial persistent data (such as user edits) to storage. However, you should be selective about
what information must be retained during <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code>, because any
blocking procedures in this method block the transition to the next activity and slow the user
experience.</p>
<p>“完成后可否杀死”一栏表明在该方法未执行一行代码的情况下系统是否会杀死该Activity。三个方法标注为“是”：onPause()，onStop()和onDestroy()。由于onPause()是三个中的第一个，一旦Activity被创建，onPause()方法是能够保证在进程被杀死前被调用的最后一个方法——如果紧急情况下系统回收内存，那么onStop()和onDestory()方法将不再会被调用。因此，需要使用onPause()方法来将关键数据（如用户编辑）写入到存储区。然而，在onPause()方法中要有选择地将信息进行保存，因为这个方法执行过程将会延缓切换到下一个Activity，减慢用户体验。</p>

<p> Methods that are marked "No" in the <b>Killable</b> column protect the process hosting the
activity from being killed from the moment they are called.  Thus, an activity is killable
from the time <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> returns to the time
<code><a href="../../../reference/android/app/Activity.html#onResume()">onResume()</a></code> is called. It will not again be killable until
<code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> is again called and returns. </p>
<p>在“完成后可否杀死”一栏中标注为“否”的方法能够保护进程不被系统所杀死。因此，从onPause()返回到onResume()的时候，Activity是可以被杀死的。直到onPause()方法被再次调用并返回，它才会被杀死。</p>

<p class="note"><strong>Note:</strong> An activity that's not technically "killable" by this
definition in table 1 might still be killed by the system&mdash;but that would happen only in
extreme circumstances when there is no other recourse. When an activity might be killed is
discussed more in the <a
href="../../../guide/topics/fundamentals/processes-and-threads.html">Processes and
Threading</a> document.</p>


<h3 id="SavingActivityState">Saving activity state 保存activity状态</h3>

<p>The introduction to <a href="#Lifecycle">Managing the Activity Lifecycle</a> briefly mentions
that
when an activity is paused or stopped, the state of the activity is retained. This is true because
the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> object is still held in memory when it is paused or
stopped&mdash;all information about its members and current state is still alive. Thus, any changes
the user made within the activity are retained in memory, so that when the activity returns to the
foreground (when it "resumes"), those changes are still there.</p>
<p>在Activity生命周期管理中简单地提到Activity暂停或停止时，Activity的状态将会被保存。确实如此，因为Activity对象在暂停或停止时仍占用着内存——所有成员的信息以及现行状态仍是激活状态。因此，用户在Activity中做的所有修改都会保存在内存中，那么Activity重新回到前端显示（也就是重启）后，这些改变仍然是存在的。</p>

<div class="figure" style="width:615px">
<img src="../../../images/fundamentals/restore_instance.png" alt="" />
<p class="img-caption"><strong>Figure 2.</strong> The two ways in which an activity returns to user
focus with its state intact: either the activity is stopped, then resumed and the activity state
remains intact (left), or the activity is destroyed, then recreated and the activity must restore
the previous activity state (right).</p>
</div>

<p>However, when the system destroys an activity in order to recover memory, the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> object is destroyed, so the system cannot simply resume it with its state
intact. Instead, the system must recreate the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> object if the user
navigates back to it. Yet, the user is unaware
that the system destroyed the activity and recreated it and, thus, probably
expects the activity to be exactly as it was. In this situation, you can ensure that
important information about the activity state is preserved by implementing an additional
callback method that allows you to save information about the state of your activity and then
restore it when the the system recreates the activity.</p>
<p>然而，系统回收内存而销毁Activity时，Activity对象会被销毁，因此系统就不能简单地原封不动地重启该Activity。这样子，用户想要导航回去，系统就必须重建Activity对象。然而用户并不会意识到系统销毁和重建Activity，而期待Activity和之前一模一样。这种情况下，通过实现外加的回调方法来对Activity状态信息进行保存，以便系统重建Activity时能够使用这些状态信息。</p>

<p>The callback method in which you can save information about the current state of your activity is
<code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code>. The system calls this method
before making the activity vulnerable to being destroyed and passes it
a <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> object. The <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> is where you can store 
state information about the activity as name-value pairs, using methods such as <code><a href="../../../reference/android/os/Bundle.html#putString(java.lang.String, java.lang.String)">putString()</a></code>. Then, if the system kills your activity's
process and the user navigates back to your activity, the system passes the <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> to <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> so you can restore the
activity state you saved during <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code>. If there is no state information to restore, then the <code><a href="../../../reference/android/os/Bundle.html">Bundle</a></code> passed to <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code> is null.</p>
<p>在onSaveInstanceState()回调方法中可以保存当前Activity的状态信息。在Activity自愿被销毁之前，系统会调用这个方法，传递一个Bundle对象。而在Bundle中使用类似putString()方法可以以键值对的形式来保存状态信息。然后，如果系统杀死Activity并且用户导航返回，系统会传递Bundle对象到onCreate()方法，这样就可以在onSaveInstanceState()方法中重建已保存的Activity状态。如果没有重建的状态系统，那么Bundle传递给onCreate()方法将是空值。</p>

<p class="note"><strong>Note:</strong> There's no guarantee that <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code> will be called before your
activity is destroyed, because there are cases in which it won't be necessary to save the state
(such as when the user leaves your activity using the BACK key, because the user is explicitly
closing the activity). If the method is called, it is always called before <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> and possibly before <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code>.</p>
<p class="note"><strong>Note:</strong>并不能保证一定会调用onSaveInstanceState()方法，然后才销毁Activity，因此有时候没必要保存这些状态（比如用户使用返回键离开Activity，就是想关掉该Activity）。调用该方法都是在onStop()方法之前，也可能在onPause()方法之前。</p>

<p>However, even if you do nothing and do not implement <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code>, some of the activity state is
restored by the <code><a href="../../../reference/android/app/Activity.html">Activity</a></code> class's default implementation of <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code>. Specifically, the default
implementation calls <code><a href="../../../reference/android/view/View.html#onSaveInstanceState()">onSaveInstanceState()</a></code> for every <code><a href="../../../reference/android/view/View.html">View</a></code>
in the layout, which allows each view to provide information about itself
that should be saved. Almost every widget in the Android framework implements this method as
appropriate, such that any visible changes to the UI are automatically saved and restored when your
activity is recreated. For example, the <code><a href="../../../reference/android/widget/EditText.html">EditText</a></code> widget saves any text
entered by the user and the <code><a href="../../../reference/android/widget/CheckBox.html">CheckBox</a></code> widget saves whether it's checked or
not. The only work required by you is to provide a unique ID (with the <a
href="../../../guide/topics/resources/layout-resource.html#idvalue"><code>android:id</code></a>
attribute) for each widget you want to save its state. If a widget does not have an ID, then it
cannot save its state.</p>
<p>然而，即使什么都不做，不实现onSaveInstanceState()方法，Activity的部分状态信息仍会被Activity类的默认onSaveInstanceState()方法保存下来。特别地，默认onSaveInstanceState()方法会为布局中的每个View进行保存，这样可以让每个view能够提供自己应该保存的信息。Android框架里，几乎每个windget都适当地实现该方法对UI的可见修改都会自动地保存，并在重建Activity时使用。比如，EditText这个widget会保存用户输入的所有文字，而CheckBox这个widget会保存是否已被选择。唯一要做的就是为需要保存状态的每个widget设置唯一的ID。如果没有ID，那么就不会保存它的状态。</p>

<div class="sidebox-wrapper">
<div class="sidebox">
<p>You can also explicitly stop a view in your layout from saving its state by setting the
<code><a href="../../../reference/android/R.attr.html#saveEnabled">android:saveEnabled</a></code> attribute to <code>"false"</code> or by calling
the <code><a href="../../../reference/android/view/View.html#setSaveEnabled(boolean)">setSaveEnabled()</a></code> method. Usually, you should not
disable this, but you might if you want to restore the state of the activity UI differently.</p>
</div>
</div>

<p>Although the default implementation of <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code> saves useful information about
your activity's UI, you still might need to override it to save additional information.
For example, you might need to save member values that changed during the activity's life (which
might correlate to values restored in the UI, but the members that hold those UI values are not
restored, by default).</p>
<p>尽管默认onSaveInstanceState()方法保存Activity UI的有用信息，有时候可能仍需要重写来保存额外的信息。比如，可能需要保存在Activity生命中被修改了的成员变量的值（这可能和存储在UI中的数值没关系，但是默认情况下这些值并不会被保存在UI值里面）。</p>

<p>Because the default implementation of <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code> helps save the state of the UI, if
you override the method in order to save additional state information, you should always call the
superclass implementation of <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code>
before doing any work.</p>
<p>因为默认onSaveInstanceState()方法会保存UI的状态,如果为了保存额外状态信息而重写该方法，首先要做的应该是调用超类中的onSaveInstanceState()函数。</p>

<p class="note"><strong>Note:</strong> Because <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code> is not guaranteed
to be called, you should use it only to record the transient state of the activity (the state of
the UI)&mdash;you should never use it to store persistent data.  Instead, you should use  <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> to store persistent data (such as data that should be saved
to a database) when the user leaves the activity.</p>
<p class="note"><strong>Note:</strong>由于onSaveInstanceState()方法并不能保证一定会调用，所以只有在记录短暂状态（UI状态）时才会使用——千万别用来保存常用数据。相反，应该使用onPause()方法来保存用户离开Activity时的常用数据（如哪些应该保存到数据库中的数据）。</p>

<p>A good way to test your application's ability to restore its state is to simply rotate the
device so that the screen orientation changes. When the screen orientation changes, the system
destroys and recreates the activity in order to apply alternative resources that might be available
for the new orientation. For this reason alone, it's very important that your activity
completely restores its state when it is recreated, because users regularly rotate the screen while
using applications.</p>
<p>简单地旋转设备改变屏幕，就能够测试程序是否能够存储状态信息。当屏幕方向改变时，为了应用可能会在此方向状态下的资源，系统会销毁并重建Activity。仅此原因，Activity完全地重建状态就尤为重要，因为用户在使用程序时旋转了屏幕方向。</p>


<h3 id="ConfigurationChanges">Handling configuration changes掌控配置文件的变化</h3>

<p>Some device configurations can change during runtime (such as screen orientation, keyboard
availability, and language). When such a change occurs, Android restarts the running Activity
(<code><a href="../../../reference/android/app/Activity.html#onDestroy()">onDestroy()</a></code> is called, followed immediately by <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code>). The restart behavior is
designed to help your application adapt to new configurations by automatically reloading your
application with alternative resources that you've provided. If you design your activity to
properly handle this event, it will be more resilient to unexpected events in the activity
lifecycle.</p>
<p>有些设备在运行时配置会有所变化（比如屏幕方向，键盘启用和语言）。有这些变化时，Android会重启正在运行的Activity（先调用onDestory()，迅速地执行onCreate()方法）。这样重启可以通过自动重新加载程序以及资源，让程序更好地适应新的配置信息。如果Activity能够恰当地控制此类事件，在整个生命周期中对于突发事件就会更加地灵活。</p>

<p>The best way to handle a configuration change, such as a change in the screen orientation, is
  to simply preserve the state of your application using <code><a href="../../../reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)">onSaveInstanceState()</a></code> and <code><a href="../../../reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)">onRestoreInstanceState()</a></code> (or <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code>), as discussed in the previous section.</p>
  <p>掌控配置变化的最好办法是，使用上面讲到的onSaveInstanceState()和onRestoreInstanceState()或是onCreate()来简单地保存程序的状态信息。</p>

<p>For a detailed discussion about configuration changes that happen at runtime and how you should
handle them, read <a href="../../../guide/topics/resources/runtime-changes.html">Handling
Runtime Changes</a>.</p>



<h3 id="CoordinatingActivities">Coordinating activities 协调activity</h3>

 <p>When one activity starts another, they both experience lifecycle transitions. The first activity
pauses and stops (though, it won't stop if it's still visible in the background), while the other
activity is created. In case these activities share data saved to disc or elsewhere, it's important
to understand that the first activity is not completely stopped before the second one is created.
Rather, the process of starting the second one overlaps with the process of stopping the first
one.</p>
<p>一个Activity启动另一个的时候，它们都会经历生命周期切换。第一个Activity暂停并在第二个Activity创建时停止（然而，如果仍在背景里可见那么就不会停止）。只有这些Activity共用保存在磁盘上的数据时，认识到在第二次Activity创建之前第一个并未完全地停止这一点是很重要的。而且启动第二个Activity的同时将会停止第一个Activity。</p>

<p>The order of lifecycle callbacks is well defined, particularly when the two activities are in the
same process and one is starting the other. Here's the order of operations that occur when Activity
A starts Acivity B: </p>
<p>生命周期回调的顺序定义得很明确，特别是一个过程中有两个Activity，一个启动另一个Activity的时候。下面是Activity A启动Activity B时的操作顺序：</p>

<ol>
<li>Activity A's <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> method executes.
<p>A的onPause()方法被执行</p></li>

<li>Activity B's <code><a href="../../../reference/android/app/Activity.html#onCreate(android.os.Bundle)">onCreate()</a></code>, <code><a href="../../../reference/android/app/Activity.html#onStart()">onStart()</a></code>, and <code><a href="../../../reference/android/app/Activity.html#onResume()">onResume()</a></code>
methods execute in sequence. (Activity B now has user focus.)
<p>B的onCreate()，onStart()，onResume()方法被按照顺序执行。</p></li>

<li>Then, if Activity A is no longer visible on screen, its <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code> method executes.
<p>如果长时间不在屏幕上查看A，那么A的onStop()方法执行。</p></li>
</ol>

 <p>This predictable sequence of lifecycle callbacks allows you to manage the transition of
information from one activity to another. For example, if you must write to a database when the
first activity stops so that the following activity can read it, then you should write to the
database during <code><a href="../../../reference/android/app/Activity.html#onPause()">onPause()</a></code> instead of during <code><a href="../../../reference/android/app/Activity.html#onStop()">onStop()</a></code>.</p>
<p>这些预设好的生命周期回调有助于对Activity切换时的信息进行管理。比如，在第一个Activity停止时想要往数据库里写数据，以便后一个Activity能够读取，那么就要在onPause()方法中写到数据库，而不是在onStop()方法中。</p>

<!--
<h2>Beginner's Path</h2>

<p>For more information about how Android maintains a history of activities and
enables user multitasking, continue with the <b><a
href="../../../guide/topics/fundamentals/tasks-and-back-stack.html">Tasks and Back
Stack</a></b> document.</p>
-->
    </div>

  <a href="#top" style="float:right">&uarr; Go to top</a>
  
  </div>

<div id="footer">


  <div id="copyright">
    
  Except as noted, this content is licensed under <a
  href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a>. 
  For details and restrictions, see the <a href="../../../license.html">
  Content License</a>.
  </div>
  <div id="build_info">
    
  Android 4.0&nbsp;r1 - 17 Oct 2011 18:17

  </div>

  <div id="footerlinks">
    
  <p>
    <a href="http://www.android.com/terms.html">Site Terms of Service</a> -
    <a href="http://www.android.com/privacy.html">Privacy Policy</a> -
    <a href="http://www.android.com/branding.html">Brand Guidelines</a>
  </p>
  </div>

</div> <!-- end footer -->

</div><!-- end doc-content -->

</div> <!-- end body-content --> 

<script type="text/javascript">
init(); /* initialize android-developer-docs.js */
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-5831155-1");
pageTracker._trackPageview();
</script>

</body>
</html>



